﻿

@using SubstrateHelper.Data;
@using SubstrateHelper.Models;
@using ProcessBase.Models;
@using System.Collections.Concurrent;
@using System.Collections.Generic;
@using System.Linq;
@using System.Timers;


@inject SubstrateHelperDbContext Db
@inject MessageService MessageService
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject UserManager<IdentityUser> UserManager
@inject NavigationManager NavigationManager

<div class="m-1">
    <span>
        <strong class="text-success">基板型号 </strong>：
        <select @bind="SelectedSubstrateType">
            <option value="-1">所有类型</option>
            @if (SubstrateTypes != null)
            {
                @for (int i = 0; i < SubstrateTypes.Count; i++)
                {
                    <option value="@i">@SubstrateTypes[i]</option>
                }
            }

        </select>
    </span>

    <span class="ml-5">
        <strong class="text-success">订单号 </strong>包含：
        <input type="text" @bind="OrderCode" style="width:100px">
    </span>

    <span class="ml-5">
        <strong class="text-success">批号 </strong>包含：
        <input type="text" @bind="LotNo" style="width:100px">
    </span>

    <span class="ml-5">
        <strong class="text-success">关闭状态 </strong>：
        <select @bind="ClosedState">
            <option value="-1">所有</option>
            <option value="0">未关闭</option>
            <option value="1">已关闭</option>
        </select>
    </span>




</div>
<div class="m-1 mt-3">

    <span><strong class="text-success">下单日期 </strong>从：<input type="date" @bind="OrderDateStart"></span>
    <span class="ml-1">至：<input type="date" @bind="OrderDateEnd"></span>

    <span class="ml-5"><strong class="text-success">关闭日期 </strong>从：<input type="date" @bind="OrderDateStart"></span>
    <span class="ml-1">至：<input type="date" @bind="OrderDateEnd"></span>



    <Button class="ml-5" IsOutline="false" Color="Color.Success" @onclick="DoQuery">查  询</Button>
</div>
<hr class="bg-primary" style="height:5px;" />
<div class="container-fluid">
    <div class="row justify-content-end">
        <h4 class="text-primary">共选择<strong class="text-danger">@SelectedCount</strong>条订单</h4>
        <button class="btn btn-primary ml-5 mr-10 mb-1" @onclick="OnClose">关闭（入库完毕）</button>
    </div>
    <div class="row mt-2">
        <Table TItem="ProcessBase.Models.Order" @ref="TheTable"
               IsPagination="true" PageItemsSource="@PageItemsSource"
               IsStriped="true" IsBordered="true"
               ShowToolbar="false" IsMultipleSelect="true"
               ShowDeleteButton="false"
               ShowEditButton="false"
               Items="Items"
               OnQueryAsync="@OnQueryAsync"
               Height="480">

            <TableColumns>
                @*基板类型*@
                <TableColumn @bind-Field="@context.name" Sortable="true" />
                @*订单号*@
                <TableColumn @bind-Field="@context.vbmobillcode" Sortable="true" />
                @*批次号*@
                <TableColumn @bind-Field="@context.vbatchcode" Sortable="true" />
                @*下单日期*@
                <TableColumn @bind-Field="@context.OrderBillDate" Sortable="true" FormatString="yyyy-MM-dd" />
                @*计划数量*@
                <TableColumn @bind-Field="@context.QuantityPlanned" Sortable="true" />

                @*入库数量*@
                <TableColumn @bind-Field="@context.QuantityDone" Sortable="true" />

                @*关闭日期*@
                <TableColumn @bind-Field="@context.OrderCloseDate" Sortable="true" FormatString="yyyy-MM-dd" />

            </TableColumns>



        </Table>

    </div>

</div>

<Message />
@code {

    //基板类型
    List<string> SubstrateTypes
    {
        get
        {
            if (_SubstrateTypes == null)
            {
                _SubstrateTypes = Db.CandidateLists.Where(x => x.Category == "基板类型").Select(x => x.Candidate).OrderBy(x => x).ToList();
            }
            return _SubstrateTypes;
        }
    }
    List<string> _SubstrateTypes = null;
    int SelectedSubstrateType = -1;

    //订单号
    string OrderCode { get; set; }

    //批次号
    string LotNo { get; set; }

    //下单时间
    DateTime? OrderDateStart { get; set; }
    DateTime? OrderDateEnd { get; set; }

    //关闭时间
    DateTime? CloseDateStart { get; set; }
    DateTime? CloseDateEnd { get; set; }

    //是否关闭
    int ClosedState { get; set; } = -1;

    //生产订单
    List<ProcessBase.Models.Order> Items { get; set; } = new List<Order>();



    int SelectedCount { get; set; }
    System.Timers.Timer Timer;

    string user;
    protected override async Task OnInitializedAsync()
    {
        //
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var User = authState.User;

        user = UserManager.GetUserId(User);

        //
        Timer = new System.Timers.Timer(500);
        Timer.Elapsed += (o, e) =>
        {
            InvokeAsync(() =>
            {
                if (TheTable != null)
                {
                    var selected = TheTable.SelectedRows;
                    if (selected != null)
                    {
                        SelectedCount = selected.Count();

                    }
                    else
                    {
                        SelectedCount = 0;
                    }
                }
                else
                {
                    SelectedCount = 0;
                }
                StateHasChanged();
            });


        };
        Timer.Enabled = true;
    }


    private Table<ProcessBase.Models.Order> TheTable;
    protected IEnumerable<int> PageItemsSource => new int[] { 50, 100, 200 };

    private static readonly ConcurrentDictionary<Type, Func<IEnumerable<ProcessBase.Models.Order>, string, SortOrder, IEnumerable<ProcessBase.Models.Order>>> SortLambdaCache = new ConcurrentDictionary<Type, Func<IEnumerable<ProcessBase.Models.Order>, string, SortOrder, IEnumerable<ProcessBase.Models.Order>>>();
    protected ProcessBase.Models.Order SearchModel { get; set; } = new ProcessBase.Models.Order();

    protected Task<QueryData<ProcessBase.Models.Order>> OnQueryAsync(QueryPageOptions options)
    {
        if (Items == null)
        {
            return Task.FromResult(new QueryData<ProcessBase.Models.Order>());
        }

        IEnumerable<ProcessBase.Models.Order> items = Items;

        // 过滤
        var isFiltered = false;
        if (options.Filters.Any())
        {
            items = items.Where(options.Filters.GetFilterFunc<ProcessBase.Models.Order>());
            isFiltered = true;
        }

        // 排序
        var isSorted = false;
        if (!string.IsNullOrEmpty(options.SortName))
        {
            // 外部未进行排序，内部自动进行排序处理
            var invoker = SortLambdaCache.GetOrAdd(typeof(ProcessBase.Models.Order), key => LambdaExtensions.GetSortLambda<ProcessBase.Models.Order>().Compile());
            items = invoker(items, options.SortName, options.SortOrder);
            isSorted = true;
        }

        // 设置记录总数
        var total = items.Count();

        // 内存分页
        items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();

        return Task.FromResult(new QueryData<ProcessBase.Models.Order>()
        {
            Items = items,
            TotalCount = total,
            IsSorted = isSorted,
            IsFiltered = isFiltered
        });
    }

    private async Task OnClose()
    {

        if (!_IsScheduler())
        {
            MessageService?.Show(new MessageOption()
            {
                Content = $"发生错误：您登录的用户不包含“调度员”角色。",
                Icon = "fa fa-info-circle",
                ShowDismiss = true,
                Color = Color.Danger
            });
            return;
        }

        using (var trans = Db.Database.BeginTransaction())
        {

            try
            {
                foreach (var item in TheTable.SelectedRows)
                {
                    item.OrderCloseDate = DateTime.Now.Date;
                }


                Db.SaveChanges();
                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();//数据库回滚
                MessageService?.Show(new MessageOption()
                {
                    Content = $"发生错误：{ex.Message}",
                    Icon = "fa fa-info-circle",
                    ShowDismiss = true,
                    Color = Color.Danger
                });
            }

        }


        //写入NC，使行状态为“完工”



    }



    bool _IsScheduler()
    {
        return Helpers.UserHelper.HasRole(user, "调度员");

    }

    bool _IsCangGuanYuan()
    {
        return Helpers.UserHelper.HasRole(user, "仓管员");
    }

    private async Task DoQuery()
    {
        IQueryable<ProcessBase.Models.Order> orders = Db.Orders;
        //基板类型
        if (SelectedSubstrateType >= 0)
        {
            orders = orders.Where(x => x.name == SubstrateTypes[SelectedSubstrateType]);
        }

        //订单号
        if (!string.IsNullOrWhiteSpace(OrderCode))
        {
            orders = orders.Where(x => x.vbmobillcode.Contains(OrderCode));
        }

        //批次号
        if (!string.IsNullOrWhiteSpace(LotNo))
        {
            orders = orders.Where(x => x.vbatchcode.Contains(LotNo));
        }

        //关闭状态
        if (ClosedState >= 0)
        {
            if (ClosedState == 0)
            {
                orders = orders.Where(x => x.OrderCloseDate == null);
            }
            else
            {
                orders = orders.Where(x => x.OrderCloseDate != null);
            }
        }

        //下单时间
        if (OrderDateStart != null)
        {
            orders = orders.Where(x => x.OrderBillDate >= OrderDateStart.Value);
        }
        if (OrderDateEnd != null)
        {
            orders = orders.Where(x => x.OrderBillDate <= OrderDateEnd.Value);
        }


        //关闭时间
        if (CloseDateStart != null)
        {
            orders = orders.Where(x => x.OrderCloseDate != null && x.OrderCloseDate >= CloseDateStart.Value);
        }

        if (CloseDateEnd != null)
        {
            orders = orders.Where(x => x.OrderCloseDate != null && x.OrderCloseDate <= CloseDateEnd.Value);
        }

        Items = orders.ToList();

    }
}
